package com.bjpowernode.web.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Component // Spring自动扫描，并交给容器管理
public class LoginInterceptor implements HandlerInterceptor {

    // 方法上的注解要想被Spring解析，则类上必须有Spring的注解
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private ObjectMapper objectMapper;

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 获取请求方式
        String method = request.getMethod();
        // 跨域请求的预检（服务器是否允许跨域）操作
        if (method.equalsIgnoreCase("options")) {
            return true;
        }

        // 客户端标识默认从请求头中获取
        String token = request.getHeader("token");

        // 如果是传统请求，通过后端强制跳转(异步请求只能通过前端跳转)
        Boolean isSync = request.getHeader("X-Requested-With") == null;

        // 传统请求时，客户端的标识不在请求头中，而是作为参数传递
        if (isSync) {
            token = request.getParameter("token");
        }
        if (StringUtils.isBlank(token) || redisTemplate.opsForValue().get(token) == null) {
            if (isSync) {
                String redirectUrl = request.getRequestURL().toString();
                String queryString = request.getQueryString();
                if (StringUtils.isNotBlank(queryString)) {
                    redirectUrl = redirectUrl + "?" + queryString;
                }
                redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8");
                response.sendRedirect("http://localhost:8080/login?type=redirect&redirectUrl="+redirectUrl);
                return false;
            }

            Map respMap = new HashMap();
            respMap.put("success", false);
            respMap.put("message", "请登录！");

            // 认证失败之后的操作
            respMap.put("op", "login");

            String json = objectMapper.writeValueAsString(respMap);

            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().write(json);

            // 拦截请求
            return false;
        }

        // 放行
        return true;
    }
}
